#!/bin/bash

# Helper script used to run cheops on Amazon EC2
# $CONFIG_PY is a environment variable which contains the config.py URL
# $OUTPUT: output file prefix
# $ERRORS: errors file prefix

OUTPUT=~/log
ERRORS=~/log
user=$(whoami)
ts=$(date +%Y_%m_%d_%H_%M_%S_%z)

if [ ! -f ./counter ]; then
  COUNTER=1
else
  COUNTER=$(cat counter)
  COUNTER=$(( $COUNTER+1 ))
fi
echo $COUNTER > ./counter

ami_id=$(curl --silent http://169.254.169.254/latest/meta-data/ami-launch-index)
ct=$(printf %06d $COUNTER)
aid=$(printf %06d ${ami_id})
out=${OUTPUT}_${ct}_${aid}_${user}_${ts}.output
err=${ERRORS}_${ct}_${aid}_${user}_${ts}.errors
prof=${ERRORS}_${ct}_${aid}_${user}_${ts}.profile

killall python
killall python

sudo apt-get -qq update 
# sudo apt-get -qq upgrade
sudo apt-get -qq install mercurial s3cmd

if [ -d cheops ];
then
    cd cheops && hg pull && hg update;
else
    hg clone https://cheops.googlecode.com/hg/ cheops && cd cheops
fi
rm *.ckpt
if [ ${ami_id} -eq 0 ]; then
        nohup python dispatcher.py > $out 2> $err &
else
        nohup python main.py ${ami_id} > $out 2> $err &
fi
cd ..
echo $out 
